package h0903;

import java.util.Arrays;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 种花问题
 * @date 2024/9/3 23:28
 */
public class PlantFlowers {
    public static void main(String[] args) {
        int[] flowered = {0, 0, 1, 0, 0, 0, 1, 0, 0};
        int n = 2;
        System.out.println(canPlaceFlowers2(flowered, n));
    }

    public static boolean canPlaceFlowers(int[] flowerbed, int n) {
        int[] flowers = new int[flowerbed.length + 4];
        flowers[0] = 1;
        flowers[1] = 0;
        flowers[flowers.length - 1] = 1;
        flowers[flowers.length - 2] = 0;
        for (int i = 2; i < flowers.length - 2; i++) {
            flowers[i] = flowerbed[i - 2];
        }

        int start = 0;
        int count = 0;
        int ans = 0;
        for (int end = 0; end < flowers.length; end++) {
            if (count >= 3) {
                ans += Math.ceil((double) count / 3);
                count = 0;
            }
            if (flowers[end] == 0) {
                count++;
            } else if (flowers[end] == 1) {
                count = 0;
            }
        }
        return ans >= n;
    }

    public static boolean canPlaceFlowers2(int[] flowerbed, int n) {
        int count = 0;
        for (int i = 0; i < flowerbed.length; i++) {
            //TODO 判断连续的三个数是否是0，边界情况:flowerbed[i] == 0;i == 0;flowerbed[i + 1] == 0
            //TODO flowerbed[i - 1] == 0;i == flowerbed.length - 1
            if (flowerbed[i] == 0 &&
                    (i == 0 || flowerbed[i - 1] == 0) &&
                    (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i] = 1;
                count++;
                if (count >= n) {
                    return true;
                }
            }
        }
        return count >= n;
    }
}
